package org.onvivals.module.iot.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.common.enums.BillDetailEnum;
import org.onvivals.common.utils.CommonUtil;
import org.onvivals.module.iot.entity.IotDevice;
import org.onvivals.module.iot.mapper.IotDeviceMapper;
import org.onvivals.module.iot.service.IIotDeviceService;
import org.onvivals.module.pms.entity.PmsRole;
import org.onvivals.module.pms.entity.PmsRoleIndividuality;
import org.onvivals.module.pms.service.IPmsCodeService;
import org.onvivals.module.pms.service.IPmsRoleIndividualityService;
import org.onvivals.module.pms.service.IPmsRoleService;
import org.onvivals.module.ums.entity.UmsUser;
import org.onvivals.module.ums.service.IUmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class IotDeviceServiceImpl extends ServiceImpl<IotDeviceMapper, IotDevice> implements IIotDeviceService {

	@Autowired
	private IUmsUserService umsUserService;

	@Autowired
	private IPmsCodeService pmsCodeService;

	@Autowired
	private IPmsRoleService roleService;

	@Autowired
	private IPmsRoleIndividualityService roleIndividualityService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean insertDeviceAuto(String serialNumber, Long userId,String code,String blId) {
		UmsUser member = umsUserService.getById(userId);
		boolean flag = pmsCodeService.checkCode(code, userId);
		PmsRole pmsRole = roleService.getOne(Wrappers.<PmsRole>lambdaQuery().eq(PmsRole::getIsDefault, true),false);
		List<PmsRoleIndividuality> list = roleIndividualityService.list(Wrappers.<PmsRoleIndividuality>lambdaQuery().eq(PmsRoleIndividuality::getRoleId, pmsRole.getId()));
		PmsRoleIndividuality pmsRoleIndividuality = CommonUtil.listGetOne(list);
		if (!flag){
			return false;
		}
		// 设备认证后自动添加设备
		IotDevice device = this.selectDeviceBySerialNumber(serialNumber);
		if (device==null){
			device = new IotDevice();
			device.setDeviceName("未知");
			device.setSerialNumber(serialNumber);
			device.setUserId(userId);
			device.setUserName(member.getUsername());
			device.setActiveTime(new Date());
			device.setStatus(3);
			device.setRoleId(pmsRole.getId());
			device.setIndividualityId(pmsRoleIndividuality.getId());
			device.setVolume(50);
			device.setRms(200);
			device.setBlId(blId);

			boolean saveFlag = this.save(device);

			if (saveFlag) {
				//获取当前用户vip时间
				Date vipExpireTime = member.getVipExpireTime();
				if (vipExpireTime != null) {
					//更新用户vip时间
					Date newVipExpireTime = DateUtil.offsetMonth(vipExpireTime, 3);
					member.setVipExpireTime(newVipExpireTime);
				} else {
					//更新用户vip时间
					Date newVipExpireTime = DateUtil.offsetMonth(new Date(), 3);
					member.setVipExpireTime(newVipExpireTime);
				}
				umsUserService.updateById(member);
			}

		}else {
			if (device.getStatus() ==1 ){
				device.setDeviceName("未知");
				device.setUserId(userId);
				device.setUserName(member.getUsername());
				device.setActiveTime(new Date());
				device.setStatus(3);
				device.setRoleId(pmsRole.getId());
				device.setIndividualityId(pmsRoleIndividuality.getId());
				device.setVolume(50);
				device.setRms(200);
				device.setBlId(blId);
				this.updateById(device);

			}else {
				if(ObjectUtil.isNotEmpty(device.getUserId())){
					if (!Objects.equals(userId, device.getUserId())) {
						return false;
					}
				}
			}
			if (ObjectUtil.isEmpty(device.getUserId())){
				device.setUserId(userId);
				device.setUserName(member.getUsername());
				device.setRoleId(pmsRole.getId());
				device.setIndividualityId(pmsRoleIndividuality.getId());
				device.setVolume(50);
				device.setBlId(blId);
				this.updateById(device);
			}
		}
		return true;
	}

	@Override
	public IotDevice autoDevice(String deviceNumber, Long userId, String code, String blId) {
		UmsUser member = umsUserService.getById(userId);
		log.info("设备号：{} 用户id：{} 激活码：{}",deviceNumber,userId,code);
		boolean flag = pmsCodeService.checkCode(code, userId);
		PmsRole pmsRole = roleService.getOne(Wrappers.<PmsRole>lambdaQuery().eq(PmsRole::getIsDefault, true),false);
		List<PmsRoleIndividuality> list = roleIndividualityService.list(Wrappers.<PmsRoleIndividuality>lambdaQuery().eq(PmsRoleIndividuality::getRoleId, pmsRole.getId()));
		PmsRoleIndividuality pmsRoleIndividuality = CommonUtil.listGetOne(list);
		if (!flag){
			throw new RuntimeException("激活码错误");
		}
		IotDevice iotDevice = this.selectDeviceBySerialNumber(deviceNumber);
		if (iotDevice==null){
			iotDevice = new IotDevice();
			iotDevice.setDeviceName("未知");
			iotDevice.setSerialNumber(deviceNumber);
			iotDevice.setUserId(userId);
			iotDevice.setUserName(member.getUsername());
			iotDevice.setActiveTime(new Date());
			iotDevice.setStatus(3);
			iotDevice.setRoleId(pmsRole.getId());
			iotDevice.setIndividualityId(pmsRoleIndividuality.getId());
			iotDevice.setVolume(50);
			iotDevice.setRms(200);
			iotDevice.setBlId(blId);

			boolean saveFlag = this.save(iotDevice);

			if (saveFlag) {
				//获取当前用户vip时间
				Date vipExpireTime = member.getVipExpireTime();
				if (vipExpireTime != null) {
					//更新用户vip时间
					Date newVipExpireTime = DateUtil.offsetMonth(vipExpireTime, 3);
					member.setVipExpireTime(newVipExpireTime);
				} else {
					//更新用户vip时间
					Date newVipExpireTime = DateUtil.offsetMonth(new Date(), 3);
					member.setVipExpireTime(newVipExpireTime);
				}
				umsUserService.updateById(member);
			}

		}else {
			iotDevice.setBlId(blId);
			this.updateById(iotDevice);
		}
		return null;
	}

	@Override
	public IotDevice selectDeviceBySerialNumber(String serialNumber,Long userId) {
		IotDevice device = this.getOne(Wrappers.<IotDevice>lambdaQuery().eq(IotDevice::getSerialNumber, serialNumber).eq(IotDevice::getUserId,userId));
		return device;
	}

	@Override
	public IotDevice selectDeviceBySerialNumber(String serialNumber) {
		IotDevice device = this.getOne(Wrappers.<IotDevice>lambdaQuery().eq(IotDevice::getSerialNumber, serialNumber));
		return device;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean reportDevice(IotDevice device, IotDevice deviceEntity) {
		boolean result = false;
		if (deviceEntity != null) {
			device.setUpdateTime(new Date());
			if (deviceEntity.getActiveTime() == null || deviceEntity.getActiveTime().equals("")) {
				device.setActiveTime(new Date());
			}
			LambdaUpdateWrapper<IotDevice> updateWrapper = Wrappers.<IotDevice>lambdaUpdate().eq(IotDevice::getSerialNumber, device.getSerialNumber());
			// 不更新物模型
			result = this.update(device, updateWrapper);
		}
		return result;
	}

}
